package com.pansoft.openplanet.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.FileDeleteUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.WalletAccountAdapter;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 我的钱包
 * Created by will on 18-3-23.
 */
@Deprecated
public class MyWalletActivity extends TCBaseActivity implements View.OnClickListener, WalletAccountAdapter.RefreshLister {

    private RecyclerView recyclerView;
    private List<WalletBean> list;
    private final static String TAG = "MyWalletActivity";
    int requestCount = 0;
    private WalletAccountAdapter mAdapter;
    private SmartRefreshLayout refreshLayout;
    private ImageView iv_add;
    private boolean showLoading = true;
    private AccountDao accountDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_actiivty_my_wallet);
        accountDao = new AccountDao(this);
        initView();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initView();
        initData();
    }

    private void initView() {
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_asset_my_wallet_electronic_base));
        recyclerView = (RecyclerView) findViewById(R.id.recycleview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        iv_add = (ImageView) findViewById(R.id.iv_add);
        iv_add.setVisibility(View.VISIBLE);
        iv_add.setOnClickListener(this);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                showLoading = false;
                initData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.finishLoadMore();
            }
        });
    }

    private void initData() {
        list = new ArrayList<>();
        mAdapter = new WalletAccountAdapter(this, list);
        mAdapter.setRefreshListener(this);
        recyclerView.setAdapter(mAdapter);
        if (showLoading) {
            showLoading(ResStringUtil.getString(R.string.common_text_loading));
        }
        localKeyStore();
        getBanlancefromServer();

    }


    //从服务器获取余额
    private void getBanlancefromServer() {
        if (list.size() == 0) {
            refreshLayout.finishRefresh();
            dismissLoading();
            showLoading = true;
            //ToastUtil.showToast(getApplicationContext(), "请先添加新账户或者导入账户");
        } else {
            requestCount = 0;
            for (final WalletBean bean : list) {

                HashMap<String, String> map = new HashMap<>();
                map.put("ethAddress", bean.getAddress());
                TCRequestUtil.postCommonRequest(TAG, "eth/ethGetBalance", map, new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        JSONObject jsonObject = null;
                        showLoading = true;

                        try {
                            jsonObject = new JSONObject(response);
                            if (jsonObject != null && jsonObject.getString("result").equals("success")) {
                                String balance = jsonObject.getString("balance");
                                balance = BalanceUtil.balanceConvert(balance);
                                bean.setBalance(balance);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            dismissLoading();
                        }

                        requestCount += 1;
                        if (requestCount == list.size()) {
                            dismissLoading();
                            refreshLayout.finishRefresh();
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        dismissLoading();
                        showLoading = true;

                    }
                });
            }


        }
    }

    private List<WalletBean> localKeyStore() {
        String fileFloder = TalkChainConstant.getDataFilePath(this) + File.separator + EnvironmentVariable.getUserName();

        File file = new File(fileFloder);
        if (file == null) {
            return list;
        }
        if (!file.isDirectory()) {
            FileDeleteUtil.delete(file);
            file.mkdirs();
            return list;
        }
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                WalletBean walletBean = new WalletBean();
                try {
                    String text = readFile(files[i].getAbsolutePath());
                    JSONObject jsonObject = new JSONObject(text);
                    if (jsonObject != null && jsonObject.has("address")) {
                        walletBean.setAddress("0x" + jsonObject.getString("address"));
                        walletBean.setFile(files[i]);
                        walletBean.setFilePath(files[i].getAbsolutePath());
                        Account account = accountDao.getAccount(walletBean.getAddress().toLowerCase());
                        if (account!=null){
                            walletBean.setAccountName(account.getAcccountName());
                            walletBean.setAvatar(account.getAccountAvatar());
                        }else{
                            walletBean.setAccountName(ResStringUtil.getString(R.string.open_planet_asset_child_account_account));
                            walletBean.setAvatar("");
                        }

                        list.add(walletBean);
                    } else {
                        continue;
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
            return list;

        } else {
            return list;
        }


    }

    public static String readFile(String filePath) throws IOException {
        StringBuffer sb = new StringBuffer();
        readToBuffer(sb, filePath);
        return sb.toString();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_add) {
            Intent intent = new Intent(this, CreateWalletActivity.class);
            intent.putExtra("number", EnvironmentVariable.getUserName());
            intent.putExtra(CreateWalletActivity.LAST_ACTIVITY, "myWallet");

            startActivity(intent);

        }
    }

    public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
        InputStream is = new FileInputStream(filePath);
        String line; // 用来保存每行读取的内容
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        line = reader.readLine(); // 读取第一行
        while (line != null) { // 如果 line 为空说明读完了
            buffer.append(line); // 将读到的内容添加到 buffer 中
            buffer.append("\n"); // 添加换行符
            line = reader.readLine(); // 读取下一行
        }
        reader.close();
        is.close();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void refresh() {
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}